package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//继承或者实现(适配者模式)
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    //登录检查
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {

        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //1获取当前请求方法对象
        if(handler instanceof HandlerMethod){//判断是不是动态资源(拦截器只对动态资源做处理,过滤器对所有web请求做处理)
            HandlerMethod hm = (HandlerMethod)handler;
            //2判断该请求放发上是否贴了@requireLogin
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                //3如果贴了,需要进行登录检查
                if(user==null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }

        //放行,并且让所有请求都可以共享到用户信息
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}
